
'''
This module computes the sentiments based on input text.
It reads a list of sentiment depicting words from Sentiment database
and computes the sentiment value.

Author          :                Naresh Pratap Singh
E-Mail          :                MAIL2NARESH@GMAIL.COM
Date            :                Jan 17 2011
Project Advisor :                Prof. Steven Skiena
'''

import siteConfig
import errorStrings, debugTrace
import sys
import re

class sentimentPackage:

    sentimentFile                   = siteConfig.sentimentMainFile
    modifierFile                    = siteConfig.sentimentModifiersFile
    modifierDelim                   = '\t'
    sentimentDelim                  = '|'
    sentimentDict                   = {}
    modifierList                    = {}

    debugEnabled                    = False
    errorStringsInst                = None
    debugTraceInst                  = None

    def __init__(self, debugEnabled = False):
        try:
            self.debugEnabled       = debugEnabled
            self.errorStringsInst   = errorStrings.errorStrings()
            self.debugTraceInst     = debugTrace.debugTrace(self.debugEnabled)

            hSentimentFile          = open(self.sentimentFile)
            hModifierFile           = open(self.modifierFile)
            
            for line in hModifierFile.readlines():
                items               = line.split(self.modifierDelim)
                self.modifierList [items [0].lower()]    = int(items [1])

            for line in hSentimentFile.readlines():
                items               = line.split(self.sentimentDelim)
                self.sentimentDict [items [0].lower()]  = (items [1], items [2], int(items [3]))

            hSentimentFile.close()
            hModifierFile.close()
        except:
            hModifierFile.close()
            hSentimentFile.close()
            self.debugTraceInst.doPrintTrace(self.errorStringsInst.getResourceNotFoundError(), sys.exc_info() [1])

    def constructRegEx(self, wordList):
        return r'\b'+'('+'|'.join(wordList)+')'+r'\b'

    def computeSentiment(self, message):
        positiveSentiment           = 0
        negativeSentiment           = 0
        negativeWords               = []
        positiveWords               = []
        wordList                    = {}
        totalCount                  = 0
        multiplier                  = 1
        combinedWord                = ''
        wordList                    = message.split()

        try:
            for word in wordList:
                totalCount              = totalCount + 1
                lowerWord               = word.lower()

                if lowerWord in self.modifierList:
                    if len(combinedWord) != 0:
                        combinedWord    = combinedWord + ' '

                    combinedWord        = combinedWord + lowerWord
                    multiplier          = multiplier*self.modifierList [lowerWord]
                elif lowerWord in self.sentimentDict:
                    sentimentValue      = self.sentimentDict [lowerWord][2]*multiplier
                    if len(combinedWord) != 0:
                        combinedWord    = combinedWord + ' '

                    combinedWord        = combinedWord + lowerWord

                    if sentimentValue < 0:
                        negativeSentiment   += sentimentValue
                        try:
                            negativeWords.index(combinedWord)
                        except ValueError:
                            negativeWords.append(combinedWord)
                    else:
                        positiveSentiment   += sentimentValue
                        try:
                            positiveWords.index(combinedWord)
                        except ValueError:
                            positiveWords.append(combinedWord)
                    multiplier          = 1
                    combinedWord        = ''
                else:
                    multiplier          = 1
                    combinedWord        = ''
        except:
                print sys.exc_info()
        return (positiveSentiment, positiveWords, negativeSentiment, negativeWords, totalCount)

    '''
    def computeSentiment(self, message):
        positiveSentiment           = 0
        negativeSentiment           = 0
        negativeWords               = []
        positiveWords               = []
        wordList                    = {}
        totalCount                  = len(message.split(' '))
        regEx                       = self.constructRegEx(self.sentimentDict.keys())
        regObj                      = re.compile(regEx, re.IGNORECASE)
        foundWords                  = regObj.findall(message)

        for word in foundWords:
            lowerWord               = word.lower()
            sentimentValue          = self.sentimentDict [lowerWord]
            if sentimentValue [2] < 0:
                negativeSentiment   += sentimentValue [2]
                try:
                    negativeWords.index(lowerWord)
                except ValueError:
                    negativeWords.append(lowerWord)
                    
            else:
                positiveSentiment   += sentimentValue [2]
                try:
                    positiveWords.index(lowerWord)
                except ValueError:
                    positiveWords.append(lowerWord)
                   
        return (positiveSentiment, positiveWords, negativeSentiment, negativeWords, totalCount)
'''
if __name__ == "__main__":
    sent                = sentimentPackage(True)
    dir(sent)
    print sent.computeSentiment("hi This is a test program xoxo")
